package com.wxq.ams.backup.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.URL;

/**
 * MySQL备份还原工具类
 *
 * @author Louis
 * @date Sep 21, 2018
 */
public class BackupUtils {
    private static final Logger logger = LoggerFactory.getLogger(BackupUtils.class);

    /**
     * 备份数据库
     *
     * @param host             host地址，可以是本机也可以是远程
     * @param username         数据库的用户名
     * @param password         数据库的密码
     * @param backupFolderPath 备份的路径
     * @param fileName         备份的文件名
     * @param database         需要备份的数据库的名称
     * @return
     * @throws IOException
     */
    public static boolean backup(String host, String username, String password, String backupFolderPath, String fileName,
                                 String database) throws IOException {
        File backupFolderFile = new File(backupFolderPath);
        if (!backupFolderFile.exists()) {
            // 如果目录不存在则创建
            backupFolderFile.mkdirs();
        }
        if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {
            backupFolderPath = backupFolderPath + File.separator;
        }
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            logger.info("开始进行 " + database + " 数据库备份！");
            // 拼接命令行的命令
            String backupFilePath = backupFolderPath + fileName;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");
            stringBuilder.append(" -h").append(host).append(" -u").append(username).append(" -p").append(password);
            stringBuilder.append(" --result-file=").append(backupFilePath).append(" --default-character-set=utf8 ").append(database);
            //一种方式是执行mysqldump位置，由于路径有空格采用方式如下
//            String cmd = new URL("file:C:\\Program Files\\mysql-8.0.15-winx64\\bin\\").getPath();
            String cmd = new URL("file:" + ResourceUtils.getURL("classpath:mysqldump/").getPath()).getPath();
            Process process = runtime.exec(cmd + stringBuilder.toString());
            logger.info(database + " 数据库正在备份中。。。");
            //备份文件采用输出流方式
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(backupFolderPath + fileName), "utf8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {
                logger.info(database + " 数据库备份成功，备份路径：" + backupFilePath + fileName);
                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
        logger.error(database + " 数据库备份失败！");
        return false;
    }
}
